package com.wiim.libs;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog.Builder;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.BitmapFactory.Options;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.MeasureSpec;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TabHost;

import com.google.android.gms.maps.model.LatLng;
import com.wiim.common.ConstantValue;
import com.wiim.common.Utilities;
import com.wiim.connector.RestClient;
import com.wiim.interfaceapp.DialogCallBack;
import com.wiim.interfaceapp.LocationCallBack;
import com.wiim.nhapnhap.R;

public class WorldUtilities {

	private static final String YES = "Yes";

	private static final String NO = "No";

	private static final String OK = "Ok";

	public static void closeStream(final Closeable o) {

		if (o != null) {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Delete recursive.
	 * 
	 * @param fileOrDirectory
	 *            the file or directory
	 */
	public static void deleteRecursive(final File fileOrDirectory) {

		if (fileOrDirectory.isDirectory()) {
			for (File child : fileOrDirectory.listFiles()) {
				deleteRecursive(child);
			}
		}
		fileOrDirectory.delete();
	}

	/**
	 * Switch tab.
	 * 
	 * @param context
	 *            the context
	 * @param index
	 *            the index
	 */
	public static void switchTab(final Context context, final int index) {

		TabHost thCAR = (TabHost) ((Activity) context).getParent().findViewById(android.R.id.tabhost);
		thCAR.setup();
		thCAR.setCurrentTab(index);
	}

	/**
	 * Disable virtual pad.
	 * 
	 * @param activity
	 *            the activity
	 */
	public static void disableVirtualPad(final Activity activity) {

		if (activity.getCurrentFocus() != null) {
			if (activity.getCurrentFocus().getWindowToken() != null) {
				InputMethodManager immVirtualPad = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
				immVirtualPad.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
	}

	/**
	 * Gets the device id.
	 * 
	 * @param context
	 *            the context
	 * @return the device id
	 */
	public static final String getDeviceID(final Context context) {

		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String result = telephonyManager.getDeviceId();
		if (result == null) {
			return "";
		} else {
			return result;
		}
	}

	/**
	 * Gets the image path from url.
	 * 
	 * @param sURL
	 *            the s url
	 * @return the image path from url
	 */
	public static String getImagePathFromURL(final String sURL) {

		String sFilePath = null;
		try {
			URLConnection conn;
			conn = new URL(sURL).openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			String fileName = sURL.toString().substring(sURL.toString().lastIndexOf('/') + 1, sURL.toString().lastIndexOf('.'));
			File file = new File(ConstantValue.SDCARD_ROOT);
			if (!file.exists()) {
				file.mkdirs();
			}
			sFilePath = ConstantValue.SDCARD_ROOT + fileName + ".ci";
			OutputStream os = new FileOutputStream(sFilePath);
			byte[] buffer = new byte[1024];
			int byteRead = 0;
			while ((byteRead = is.read(buffer)) != -1) {
				os.write(buffer, 0, byteRead);
			}
			os.flush();
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// return loadBitmap(ctx, sFilePath, 3);
		return sFilePath;
	}

	public static Bitmap getBitmapFromURL(String src) {
		try {
			URL url = new URL(src);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			Bitmap myBitmap = BitmapFactory.decodeStream(input);
			return myBitmap;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Show dialog exit.
	 * 
	 * @param context
	 *            the context
	 * @param activity
	 *            the activity
	 * @param strTitle
	 *            the str title
	 * @param strMessage
	 *            the str message
	 */
	public static void showDialogExit(final Context context, final String title, final String message, final Activity _act) {

		Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message).setNeutralButton(YES, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(final DialogInterface dialog, final int id) {
				((Activity) context).finish();
				System.gc();
				System.exit(0);
			}
		});

		builder.setPositiveButton(NO, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(final DialogInterface dialog, final int which) {

				dialog.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.setCancelable(false);
		alert.setCanceledOnTouchOutside(false);
		alert.show();
	}

	/**
	 * Check external storage.
	 * 
	 * @return true, if successful
	 */
	public static boolean checkExternalStorage() {

		boolean bExtAvailable = false;

		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			bExtAvailable = true;
		} else {
			bExtAvailable = false;
		}

		return bExtAvailable;
	}

	/**
	 * Check internet connection.
	 * 
	 * @param context
	 *            the context
	 * @return true, if successful
	 */
	public static boolean checkInternetConnection(final Context context) {

		// SharedPreferences mPref =
		// context.getSharedPreferences(ConstantValue.APP_NAME,
		// Context.MODE_PRIVATE);
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		// test for connection
		if ((cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Gets the account.
	 * 
	 * @param accountManager
	 *            the account manager
	 * @return the account
	 */
	public static Account getAccount(final AccountManager accountManager) {

		Account[] accounts = accountManager.getAccountsByType("com.google");
		Account account;
		if (accounts.length > 0) {
			account = accounts[0];
		} else {
			account = null;
		}
		return account;
	}

	/**
	 * Gets the bitmap from path.
	 * 
	 * @param ctx
	 *            the ctx
	 * @param sFilePath
	 *            the s file path
	 * @param inSampleSize
	 *            the in sample size
	 * @return the bitmap from path
	 */
	@SuppressWarnings("deprecation")
	public static Bitmap getBitmapFromPath(final Context ctx, final String sFilePath, final int inSampleSize) {

		Bitmap bm = null;
		try {
			Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

			int sclWidth = (int) (display.getWidth() / 1.35);
			int sclHeight = (int) (display.getHeight() / 1.5);

			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inSampleSize = inSampleSize;
			opt.inJustDecodeBounds = true;

			BitmapFactory.decodeFile(sFilePath, opt);

			if (opt.outWidth > sclWidth) {
				opt.inSampleSize = opt.outWidth / sclWidth;
			}
			if (opt.outHeight > sclHeight) {
				opt.inSampleSize = opt.outHeight / sclHeight;
			}

			opt.inJustDecodeBounds = false;
			bm = BitmapFactory.decodeFile(sFilePath, opt);
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
		return bm;
	}

	/**
	 * Gets the bitmap from path.
	 * 
	 * @param sFilePath
	 *            the s file path
	 * @param maxWidth
	 *            the max width
	 * @return the bitmap from path
	 */
	public static Bitmap getBitmapFromPath(final String sFilePath, final int maxWidth) {

		Bitmap bm = null;
		try {
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(sFilePath, opt);
			if (opt.outWidth > maxWidth) {
				opt.inSampleSize = opt.outWidth / maxWidth;
			}
			opt.inJustDecodeBounds = false;
			bm = BitmapFactory.decodeFile(sFilePath, opt);
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
		return bm;
	}

	/**
	 * Gets the bitmap from string.
	 * 
	 * @param ctx
	 *            the ctx
	 * @param s
	 *            the s
	 * @param inSampleSize
	 *            the in sample size
	 * @return the bitmap from string
	 */
	@SuppressWarnings("deprecation")
	public static Bitmap getBitmapFromString(final Context ctx, final String s) {

		Bitmap myBitmap = null;
		try {
			if (s == null) {
				return null;
			}
			byte[] bytes = null;
			bytes = Base64.decode(s, Base64.DEFAULT);
			Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

			int sclWidth = display.getWidth() / 2;
			int sclHeight = display.getHeight() / 2;

			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inSampleSize = 1;
			opt.inJustDecodeBounds = true;

			BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt);

			if (opt.outWidth > sclWidth) {
				opt.inSampleSize = opt.outWidth / sclWidth;
			} else if (opt.outHeight > sclHeight) {
				opt.inSampleSize = opt.outHeight / sclHeight;
			}

			opt.inJustDecodeBounds = false;
			myBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt);
			// myBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
			opt.requestCancelDecode();
			opt = null;
			bytes = null;
			System.gc();
		} catch (OutOfMemoryError e) {
			// getBitmapFromString(s);
			System.gc();
		}
		return myBitmap;
	}

	/**
	 * Gets the bitmap from string.
	 * 
	 * @param s
	 *            the s
	 * @return the bitmap from string
	 */
	public static Bitmap getBitmapFromString(final String s) {

		try {
			if (s == null) {
				return null;
			}
			byte[] bytes = null;
			bytes = Base64.decode(s, Base64.DEFAULT);
			Bitmap myBitmap = null;
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inJustDecodeBounds = true;

			BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt);

			if (opt.outWidth > 200) {
				opt.inSampleSize = opt.outWidth / 200;
			} else if (opt.outHeight > 200) {
				opt.inSampleSize = opt.outHeight / 200;
			}

			opt.inJustDecodeBounds = false;
			myBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt);
			// myBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
			bytes = null;
			opt.requestCancelDecode();
			opt = null;
			System.gc();

			return myBitmap;
		} catch (OutOfMemoryError e) {
			// getBitmapFromString(s);
			System.gc();
		}
		return null;
	}

	/**
	 * Gets the resized bitmap.
	 * 
	 * @param bm
	 *            the bm
	 * @param newHeight
	 *            the new height
	 * @param newWidth
	 *            the new width
	 * @return the resized bitmap
	 */
	public static Bitmap getResizedBitmap(final Bitmap bm, final int newHeight, final int newWidth) {

		if (bm == null) {
			return null;
		}
		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// CREATE A MATRIX FOR THE MANIPULATION
		Matrix matrix = new Matrix();
		// RESIZE THE BIT MAP
		matrix.postScale(scaleWidth, scaleHeight);
		// RECREATE THE NEW BITMAP
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
		return resizedBitmap;
	}

	/**
	 * Checks if is valid email address.
	 * 
	 * @param sEmail
	 *            the s email
	 * @return true, if is valid email address
	 */
	public static boolean isValidEmailAddress(final String sEmail) {

		Pattern pattern = Pattern.compile("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+");
		return pattern.matcher(sEmail).matches();
	}

	public static boolean isValidateEmail(String email) {

		Pattern pattern;
		Matcher matcher;
		String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(EMAIL_PATTERN);
		matcher = pattern.matcher(email);
		return matcher.matches();

	}

	/**
	 * Parses the from date to string format date.
	 * 
	 * @param date
	 *            the date
	 * @return the string
	 */
	public static String parseFromDateToStringFormatDate(final Date date) {

		/** The date format. */

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return dateFormat.format(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dateFormat.format(new Date());
	}

	/**
	 * Parses the from date to string format time.
	 * 
	 * @param date
	 *            the date
	 * @return the string
	 */
	public static String parseFromDateToStringFormatTime(final Date date) {

		/** The date format. */

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return dateFormat.format(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dateFormat.format(new Date());
	}

	/**
	 * Parses the from string to date.
	 * 
	 * @param sDate
	 *            the s date
	 * @return the date
	 */
	public static Date parseFromStringToDate(final String sDate) {

		/** The date format. */
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return dateFormat.parse(sDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return new Date();
	}

	/**
	 * Show dialog back.
	 * 
	 * @param context
	 *            the context
	 * @param message
	 *            the message
	 * @return the alert dialog
	 */
	public static AlertDialog showDialogCallBack(final Context context, final String message, final DialogCallBack callback) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message).setNeutralButton(OK, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(final DialogInterface dialog, final int id) {

				if (null != callback) {
					callback.callBack();
				}
			}
		});
		AlertDialog alert = builder.create();
		return alert;
	}

	/**
	 * Show dialog cannot connect to server.
	 * 
	 * @param context
	 *            the context
	 * @param title
	 *            the title
	 * @param message
	 *            the message
	 * @return the alert dialog
	 */
	public static void showDialogCannotConnectToServer(final Context context, final String title, final String message) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title).setMessage(message).setNeutralButton(OK, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(final DialogInterface dialog, final int id) {

				// Do nothing.
				System.exit(0);
			}
		});
		AlertDialog alert = builder.create();
		alert.setCancelable(false);
		alert.setCanceledOnTouchOutside(false);
		alert.show();
	}

	/**
	 * Show dialog no back.
	 * 
	 * @param context
	 *            the context
	 * @param message
	 *            the message
	 * @return the alert dialog
	 */
	public static AlertDialog showDialogNoBack(final Context context, final String message) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message).setNeutralButton(OK, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(final DialogInterface dialog, final int id) {

				// Do nothing.

			}
		});
		AlertDialog alert = builder.create();
		return alert;
	}

	/**
	 * Show dialog no back.
	 * 
	 * @param context
	 *            the context
	 * @param title
	 *            the title
	 * @param message
	 *            the message
	 * @return the alert dialog
	 */
	public static AlertDialog showDialogNoBack(final Context context, final String title, final String message) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title).setMessage(message).setNeutralButton(OK, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(final DialogInterface dialog, final int id) {

				// Do nothing.
			}
		});
		AlertDialog alert = builder.create();
		return alert;
	}

	// public static String getTagFromDBByLanguage(final Activity act, final
	// String dbName, final String table, final String field, final String
	// value,
	// final String select) {
	//
	// SQLiteDatabase DB = (new SqlLiteAdapter(act,
	// dbName)).getWritableDatabase();
	// String result = "";
	// String sQuery = "";
	// if ((field != null) && (value != null)) {
	// sQuery = "select " + select + " from " + table + " where " + field + "="
	// + "'" + value + "'" + " and id_language="
	// + Utilities.getGlobalVariable(act).Language_code;
	// }
	// try {
	// Cursor cursor = DB.rawQuery(sQuery, null);
	// if (cursor.getCount() > 0) {
	// cursor.moveToNext();
	// result = cursor.getString(cursor.getColumnIndex(select));
	// cursor.deactivate();
	//
	// }
	// DB.close();
	// } catch (Exception e) {
	// if (DB != null) {
	// DB.close();
	// }
	// e.printStackTrace();
	// }
	// return result;
	// }

	// public static String getTagFromDB(final Activity act, final String
	// dbName, final String table, final String field, final String value,
	// final String select) {
	//
	// SQLiteDatabase DB = (new SqlLiteAdapter(act,
	// dbName)).getWritableDatabase();
	// String result = "";
	// String sQuery = "";
	// if ((field != null) && (value != null)) {
	// sQuery = "select " + select + " from " + table + " where " + field + "="
	// + "'" + value + "'";
	// }
	// try {
	// Cursor cursor = DB.rawQuery(sQuery, null);
	// if (cursor.getCount() > 0) {
	// cursor.moveToNext();
	// result = cursor.getString(cursor.getColumnIndex(select));
	// cursor.deactivate();
	//
	// }
	// DB.close();
	// } catch (Exception e) {
	// if (DB != null) {
	// DB.close();
	// }
	// e.printStackTrace();
	// }
	// return result;
	// }

	// public static synchronized ArrayList<Map<String, String>>
	// getCursorFromDB(final Activity act, final String dbName, final String
	// table) {
	//
	// System.out.println("started get");
	// SQLiteDatabase DB = (new SqlLiteAdapter(act,
	// dbName)).getWritableDatabase();
	// String sQuery;
	// ArrayList<Map<String, String>> result = new ArrayList<Map<String,
	// String>>();
	// sQuery = "select * from " + table;
	// Cursor cursor = null;
	// System.out.println("started query");
	// try {
	// cursor = DB.rawQuery(sQuery, null);
	// if (cursor.getCount() > 0) {
	// cursor.moveToFirst();
	// Map<String, String> resultNote;
	// while (!cursor.isAfterLast()) {
	// resultNote = new HashMap<String, String>();
	// for (int i = 0; i < cursor.getColumnCount(); i++) {
	// resultNote.put(cursor.getColumnName(i), cursor.getString(i));
	// }
	// result.add(resultNote);
	// cursor.moveToNext();
	// }
	// }
	// DB.close();
	// cursor.deactivate();
	// } catch (Exception e) {
	// if (DB != null) {
	// DB.close();
	// }
	// if (cursor != null) {
	// cursor.deactivate();
	// }
	// e.printStackTrace();
	// }
	// System.out.println("end get");
	// return result;
	// }

	public static void callNumber(final Context cont, final String number) {

		try {
			String url = "tel:" + number;
			Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
			cont.startActivity(intent);
		} catch (Throwable e) {
			// TODO: handle exception
		}
	}

	public static void copyfile(final String srFile, final String dtFile) {

		try {
			File f1 = new File(srFile);
			File f2 = new File(dtFile);
			InputStream in = new FileInputStream(f1);

			// For Append the file.
			// OutputStream out = new FileOutputStream(f2,true);

			// For Overwrite the file.
			OutputStream out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			System.out.println("File copied.");
		} catch (FileNotFoundException ex) {
			System.out.println(ex.getMessage() + " in the specified directory.");
			System.exit(0);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	public static void writeSQLiteToFile(final Context context, final ArrayList<Map<String, String>> mapList, final String fileName) {

		FileOutputStream fos = null;
		ObjectOutputStream os = null;
		try {
			fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			os = new ObjectOutputStream(fos);
			os.writeObject(mapList);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public static ArrayList<Map<String, String>> readSQLiteFromFile(final Context context, final String _fileName) {

		String fileName = _fileName;
		ArrayList<Map<String, String>> mapList = null;
		FileInputStream fis = null;
		ObjectInputStream is = null;
		try {
			fis = context.openFileInput(fileName);
			is = new ObjectInputStream(fis);

			mapList = (ArrayList<Map<String, String>>) is.readObject();
			Utilities.closeStream(fis);
			Utilities.closeStream(is);

		} catch (Throwable e) {
			e.printStackTrace();
			Utilities.closeStream(fis);
			Utilities.closeStream(is);
		}
		return mapList;
	}

	public static Object[] getListSQLFromFile(final Context cont, final String fileName) {

		ArrayList<Map<String, String>> mapList = null;
		mapList = Utilities.readSQLiteFromFile(cont, fileName);
		if (mapList == null) {
			mapList = getSQLListFileFromAsset(cont, fileName);
			Utilities.writeSQLiteToFile(cont, mapList, fileName);
		}
		return parseFromMap(mapList);
	}

	@SuppressWarnings({ "unchecked", "finally" })
	public static ArrayList<Map<String, String>> getSQLListFileFromAsset(final Context cont, final String fileName) {

		InputStream myInput = null;
		ObjectInputStream is = null;
		ArrayList<Map<String, String>> mapList = null;
		try {
			// Open your local db as the input stream
			// myInput = new BufferedInputStream(new
			// FileInputStream(ConstantValue.SDCARD_ROOT + DB_NAME));
			myInput = cont.getAssets().open(fileName);
			is = new ObjectInputStream(myInput);

			mapList = (ArrayList<Map<String, String>>) is.readObject();
			Utilities.writeSQLiteToFile(cont, mapList, fileName);
		} catch (Throwable e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			Utilities.closeStream(myInput);
			Utilities.closeStream(is);
			return mapList;
		}
	}

	public static Object[] parseFromMap(final ArrayList<Map<String, String>> map) {

		Object[] objectForReturn = new Object[map.size()];
		try {
			for (int i = 0; i < map.size(); i++) {
				objectForReturn[i] = map.get(i);
			}

		} catch (Throwable e) {
			e.printStackTrace();
		}
		return objectForReturn;
	}

	public static void sendEmail(final Context cont, final String email) {

		Intent iEmail = new Intent(Intent.ACTION_SEND);
		iEmail.putExtra(Intent.EXTRA_EMAIL, email);
		iEmail.setType("message/rfc822");
		cont.startActivity(Intent.createChooser(iEmail, "Choose an Email client :"));
	}

	public static void callPhone(final Context cont, final String phone) {

		try {
			Intent callIntent = new Intent(Intent.ACTION_CALL);
			callIntent.setData(Uri.parse("tel:" + phone));
			cont.startActivity(callIntent);
		} catch (ActivityNotFoundException activityException) {
			Log.e("helloandroid dialing example", "Call failed", activityException);
		}
	}

	public static long getContactId(Context context, long rawContactId) {
		Cursor cur = null;
		try {
			cur = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, new String[] { ContactsContract.RawContacts.CONTACT_ID },
					ContactsContract.RawContacts._ID + "=" + rawContactId, null, null);
			if (cur.moveToFirst()) {
				return cur.getLong(cur.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cur != null) {
				cur.close();
			}
		}
		return -1l;
	}

	// get name contact by number
	public static String getContactDisplayNameByNumber(String number, Context c) {
		Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
		String name = "?";

		ContentResolver contentResolver = c.getContentResolver();
		Cursor contactLookup = contentResolver.query(uri, new String[] { BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);

		try {
			if (contactLookup != null && contactLookup.getCount() > 0) {
				contactLookup.moveToNext();
				name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
				// String contactId =
				// contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
			}
		} finally {
			if (contactLookup != null) {
				contactLookup.close();
			}
		}

		return name;
	}

	// get number phone contact by name
	public static String getPhoneNumber(String name, Context context) {
		String ret = null;
		String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " like'%" + name + "%'";
		String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
		Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, selection, null, null);
		if (c.moveToFirst()) {
			ret = c.getString(0);
		}
		c.close();
		if (ret == null)
			ret = "Unsaved";
		return ret;
	}

	// save phone to contact
	public static void savePhone(Context c, String name, String number) {

		ContentValues values = new ContentValues();
		values.put(Data.DISPLAY_NAME, name);
		Uri rawContactUri = c.getContentResolver().insert(RawContacts.CONTENT_URI, values);
		long rawContactId = ContentUris.parseId(rawContactUri);
		values.clear();
		values.put(Phone.NUMBER, number);
		values.put(Phone.TYPE, Phone.TYPE_OTHER);
		values.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
		values.put(Data.RAW_CONTACT_ID, rawContactId);
		c.getContentResolver().insert(Data.CONTENT_URI, values);

		values.clear();
		values.put(Data.MIMETYPE, Data.CONTENT_TYPE);
		values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
		values.put(Data.RAW_CONTACT_ID, rawContactId);
		c.getContentResolver().insert(Data.CONTENT_URI, values);

		values.clear();
		values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
		values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
		values.put(Data.RAW_CONTACT_ID, rawContactId);
		c.getContentResolver().insert(Data.CONTENT_URI, values);
	}

	/**
	 * Gets the string from bitmap.
	 * 
	 * @param bitmap
	 *            the bitmap
	 * @param check
	 *            the check
	 * @return the string from bitmap
	 */
	// public static String getStringFromBitmap(final Bitmap bitmap, final
	// String check) {
	//
	// String s = null;
	// byte[] bytes = null;
	// ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// if (check.equalsIgnoreCase("PNG")) {
	// bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
	// } else {
	// bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
	// }
	// bytes = baos.toByteArray();
	// s = Base64.encodeToString(bytes, 1);
	// return s;
	// }

	// public static String getStringFromBitmap(final Bitmap bitmap, final
	// String check) {
	//
	// String s = null;
	// byte[] bytes = null;
	// try {
	// ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// if (check.equalsIgnoreCase("PNG")) {
	// bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
	// } else {
	// bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
	// }
	// bytes = baos.toByteArray();
	// s = Base64.encodeToString(bytes, 1);
	// } catch (Throwable e) {
	// e.printStackTrace();
	// }
	// return s;
	// }

	// @SuppressWarnings("static-access")
	// public static void saveObJectToFile(Object objectToWrite, Context con) {
	// String fileName = "demo";
	// try {
	// FileOutputStream fos = con.openFileOutput(fileName, con.MODE_PRIVATE);
	// ObjectOutputStream os;
	// os = new ObjectOutputStream(fos);
	// os.writeObject(objectToWrite);
	// os.close();
	// } catch (Throwable e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	//
	// @SuppressWarnings("unchecked")
	// public static ArrayList<BusinessDetailModel> readObjectFromFile(Context
	// con) {
	// ArrayList<BusinessDetailModel> simpleClass = null;
	// String fileName = "demo";
	// try {
	// FileInputStream fis = con.openFileInput(fileName);
	// ObjectInputStream is = new ObjectInputStream(fis);
	// simpleClass = (ArrayList<BusinessDetailModel>) is.readObject();
	// is.close();
	// } catch (Throwable e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// return simpleClass;
	// }

	public static GPSTracker gps;
	private static double latitude;
	private static double longitude;

	public static void getGPSLocation(Context _con, LocationCallBack locationCallback) {
		gps = new GPSTracker(_con);
		LatLng mCurrentPoint;
		// check if GPS enabled
		if (gps.canGetLocation()) {
			latitude = gps.getLatitude();
			longitude = gps.getLongitude();
		} else {
			latitude = 10.7358698;
			longitude = 106.71966789999999;
			gps.showSettingsAlert();
		}
		mCurrentPoint = new LatLng(latitude, longitude);
		LoadLocationAddress newTask = new LoadLocationAddress(locationCallback);
		newTask.execute(mCurrentPoint);
	}

	public static Address getLatLog(String _address, Context context) {
		String add = _address;// address of location u have
								// entered
		Address address = null;
		Geocoder geocoder = new Geocoder(context);
		try {

			List<Address> addresses = geocoder.getFromLocationName(add, 1);

			if (addresses != null && !addresses.isEmpty()) {

				address = addresses.get(0);

			} else {

			}
		} catch (IOException e) {

		}
		return address;
	}

	public static long timeDifferenceInDays(final long firstDate, final long secondDate) {
		// final long firstDateMilli = firstDate.getTimeInMillis();
		// final long secondDateMilli = secondDate.getTimeInMillis();
		final long diff = secondDate - firstDate;

		// 24 * 60 * 60 * 1000 because I want the difference in days. Change
		// as your wish.
		// final double diffDays = (double) diff / (double) (24 * 60 * 60 *
		// 1000);

		long days = diff / (24 * 60 * 60 * 1000);
		return days;
	}

	public static void recycle(ImageView iv) {
		if (iv != null) {
			Drawable drawable = iv.getDrawable();
			if (drawable instanceof BitmapDrawable) {

				Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
				if (null != bitmap && !bitmap.isRecycled()) {
					bitmap.recycle();
					bitmap = null;
					iv.setImageBitmap(null);
					iv.setImageDrawable(null);
				}

			}
		}
	}

	// public static Bitmap getBitmapFromAsset(Context context, String file) {
	// AssetManager assetManager = context.getAssets();
	// Bitmap bitmap = null;
	// InputStream istr;
	// try {
	// istr = getAssets.open(strName);
	// bitmap = BitmapFactory.decodeStream(istr);
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// return bitmap;
	// }

	public static Bitmap getBitmapFromAsset(Context context, String file) {
		Bitmap bitmap = null;
		try {
			BitmapFactory.Options op = new BitmapFactory.Options();
			op.inPreferredConfig = Bitmap.Config.ARGB_8888;

			InputStream is = context.getAssets().open(file);
			bitmap = BitmapFactory.decodeStream(is, null, op);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return bitmap;
	}

	public static Drawable getDrawableFromAsset(Context context, String path) {
		Drawable d = null;
		try {
			d = Drawable.createFromStream(context.getAssets().open(path), path);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return d;
	}

	public void recycleDrawable(Drawable drawable) {
		if (drawable instanceof BitmapDrawable) {
			BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
			Bitmap bitmap = bitmapDrawable.getBitmap();
			bitmap.recycle();
		}
	}

	// public static Bitmap getBitmapFromView(View view) {
	// Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),
	// view.getHeight(),Bitmap.Config.ARGB_8888);
	// Canvas canvas = new Canvas(returnedBitmap);
	// Drawable bgDrawable =view.getBackground();
	// if (bgDrawable!=null)
	// bgDrawable.draw(canvas);
	// else
	// canvas.drawColor(Color.WHITE);
	// view.draw(canvas);
	// // returnedBitmap.recycle();
	// return returnedBitmap;
	// }

	public static Bitmap recycleBitmapFromView(View v) {
		Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
		Canvas c = new Canvas(b);
		v.measure(v.getLayoutParams().width, v.getLayoutParams().height); // Change
																			// from
																			// original
																			// post
		v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
		v.draw(c);
		b.recycle();
		return b;
	}

	@SuppressWarnings("unused")
	private int getListViewHeight(ListView list) {
		ListAdapter adapter = list.getAdapter();

		int listviewHeight = 0;

		list.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

		listviewHeight = list.getMeasuredHeight() * adapter.getCount() + (adapter.getCount() * list.getDividerHeight());

		return listviewHeight;
	}

	public int roundInt(int number) {
		int index;
		int results = number / 2;
		int balance = number % 2;

		if (balance != 0) {
			index = results + 1;
		} else {
			index = results;
		}
		return index;
	}

	public static long checkSizeMb(File dir) {
		long result = 0;
		try {
			Stack<File> dirlist = new Stack<File>();
			dirlist.clear();

			dirlist.push(dir);

			while (!dirlist.isEmpty()) {
				File dirCurrent = dirlist.pop();

				File[] fileList = dirCurrent.listFiles();
				for (int i = 0; i < fileList.length; i++) {

					if (fileList[i].isDirectory())
						dirlist.push(fileList[i]);
					else
						result += fileList[i].length();
				}
			}

			result = result / (1024 * 1024);

		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}

	public static Boolean checkCamera(Context context) {
		PackageManager pm = context.getPackageManager();
		if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			return true;
		} else {
			return false;
		}
	}

	public static String setLanguage(String keyName) {
		String result = "";
		try {
			// result =
			// SplashScreen.keyWorldModel.getListKey().containsKey(keyName) ?
			// SplashScreen.keyWorldModel.getListKey().get(keyName).toString() :
			// "";
		} catch (Exception e) {
			// TODO: handle exception
			result = "N/A";
		}
		return result;
	}

	// kill current app
	public static void processKill(final Context context) {
		// #1. first check api level.
		int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
		if (sdkVersion < 8) {
			// #2. if we can use restartPackage method, just use it.
			ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			am.restartPackage(context.getPackageName());
		} else {
			// #3. else, we should use killBackgroundProcesses method.
			new Thread(new Runnable() {
				public void run() {
					ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
					String name = context.getApplicationInfo().processName;
					// pooling the current application process importance
					// information.
					while (true) {
						List<RunningAppProcessInfo> list = am.getRunningAppProcesses();
						if (list == null) {
							break;
						}

						for (RunningAppProcessInfo i : list) {
							if (i.processName.equals(name) == true) {
								// #4. kill the process,
								// only if current application importance is
								// less than IMPORTANCE_BACKGROUND
								if (i.importance >= RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
									am.restartPackage(context.getPackageName()); // simple
								// wrapper
								// of
								// killBackgrounProcess
								else
									Thread.yield();
								break;
							}
						}
					}
				}
			}, "Process Killer").start();
		}
	}

	/**
	 * check internet connection
	 * 
	 * @param activity
	 * @return
	 */
	public static boolean checkInternetAvailable(Activity activity) {
		ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		boolean isWifiConn = ni.isConnected();
		ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		boolean isMobileConn = ni.isConnected();

		if (isWifiConn || isMobileConn) {
			String svcUrl = RestClient.applicationUrl();

			if (connectToUrl(svcUrl)) {
				return true;
			}

			return false;
		}

		return false;

	}

	/**
	 * 
	 * @param url
	 * @return
	 */
	public static boolean connectToUrl(String siteUrl) {
		HttpURLConnection connection;
		try {
			Log.i("PGASysUtils", "connectToUrl: " + siteUrl);

			URL url = new URL(siteUrl);

			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("User-Agent", "yourAgent");
			connection.setRequestProperty("Connection", "close");
			connection.setConnectTimeout(1000);
			connection.connect();

			int respCode = connection.getResponseCode();

			// if (respCode == 200 || respCode == 404) {
			return true;
			// }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static String formatTelNumber(String TelNum) {
		// return PhoneNumberUtils.formatNumber(TelNum);
		int nLen = TelNum.length();
		if (nLen == 10) {
			String Tel1 = TelNum.substring(0, 3);
			String Tel2 = TelNum.substring(3, 6);
			String Tel3 = TelNum.substring(6, 10);
			return String.format("%s-%s-%s", Tel1, Tel2, Tel3);
		}

		if (nLen == 11) {
			String Tel1 = TelNum.substring(0, 3);
			String Tel2 = TelNum.substring(3, 7);
			String Tel3 = TelNum.substring(7, 11);
			return String.format("%s-%s-%s", Tel1, Tel2, Tel3);
		}
		return TelNum;
	}

	public static String formatMoney(int nMoney) {
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(3);
		return nf.format(nMoney);
	}

	public static String formatMoney(float nMoney) {
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(3);
		return nf.format(nMoney);
	}

	public static String formatMoney(double nMoney) {
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(3);
		return nf.format(nMoney);
	}

	public static void enableActivityAlias(Context context, String aliasNameSpace, boolean enable) {
		Log.i("PGASysUtils", "enableActivityAlias:" + aliasNameSpace + "-" + enable);

		PackageManager pkgMgr = context.getPackageManager();
		ComponentName comp = new ComponentName("com.pga", aliasNameSpace);

		pkgMgr.setComponentEnabledSetting(comp, enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
	}

	public static String format(String formatText) {
		return formatText;
	}

	public static String format(String formatText, Object param0) {
		return format(formatText, new Object[] { param0 });
	}

	public static String format(String formatText, Object param0, Object param1) {
		return format(formatText, new Object[] { param0, param1 });
	}

	public static String format(String formatText, Object param0, Object param1, Object param2) {
		return format(formatText, new Object[] { param0, param1, param2 });
	}

	public static String format(String formatText, Object param0, Object param1, Object param2, Object param3) {
		return format(formatText, new Object[] { param0, param1, param2, param3 });
	}

	public static String format(String formatText, Object param0, Object param1, Object param2, Object param3, Object param4) {
		return format(formatText, new Object[] { param0, param1, param2, param3, param4 });
	}

	public static String format(String formatText, Object param0, Object param1, Object param2, Object param3, Object param4, Object param5) {
		return format(formatText, new Object[] { param0, param1, param2, param3, param4, param5 });
	}

	public static String format(String formatText, Object[] params) {
		Object[] newParams = new Object[params.length];
		for (int i = 0; i < newParams.length; i++) {
			if (params[i] == null) {
				continue;
			}

			if (params[i].getClass().getSimpleName().equals("String")) {
				try {
					String newString = URLEncoder.encode((String) params[i], "utf-8");
					newParams[i] = newString;
				} catch (Exception e) {
					// TODO: handle exception
				}

			} else {
				newParams[i] = params[i];
			}
		}

		return String.format(formatText, newParams);
	}

	// public static AlertDialog createProgressDialog(Activity context) {
	// AlertDialog.Builder builder = new AlertDialog.Builder(context.getParent()
	// != null ? context.getParent() : context);
	// View progressView = LayoutInflater.from(context.getParent() != null ?
	// context.getParent() : context).inflate(R.layout.screen_progress_dialog,
	// null);
	// // progressView.setBackgroundDrawable(new
	// // ColorDrawable(android.graphics.Color.TRANSPARENT));
	// builder.setView(progressView);
	//
	// AlertDialog progressDialog = builder.create();
	// progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	//
	// return progressDialog;
	// }

	public static void copyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	/**
	 * 
	 * @param bmp
	 * @return
	 */
	public static byte[] getBitmapBytes(Bitmap bmp) {
		if (bmp == null) {
			return null;
		}

		int size = bmp.getRowBytes() * bmp.getHeight();
		ByteBuffer b = ByteBuffer.allocate(size);
		bmp.copyPixelsToBuffer(b);
		byte[] bytes = new byte[size];
		try {
			b.get(bytes, 0, bytes.length);
		} catch (BufferUnderflowException e) {
			// always happens
		}

		return bytes;
	}

	/**
	 * 
	 * @param bData
	 * @return
	 */
	public static Bitmap getBitmapFromBytes(byte[] bData) {
		Log.d("PGASysUtils", "getBitmapFromBytes");

		// InputStream is = new ByteArrayInputStream(bData);
		InputStream is = new ByteArrayInputStream(bData);
		BufferedInputStream buf = new BufferedInputStream(is, 8192);

		Options opts = new Options();
		opts.inJustDecodeBounds = true;
		Bitmap bm = BitmapFactory.decodeStream(buf, null, opts);
		return bm;
	}

	public static Bitmap getBitmapFromBytes(byte[] bData, int width, int height) {
		Log.d("PGASysUtils", "getBitmapFromBytes");
		InputStream is = new ByteArrayInputStream(bData);
		return BitmapFactory.decodeStream(is);
	}

	public static String getBitmapUrl(String fileId) {
		String service_url = "system/file/url/%s";
		String url = WorldUtilities.format(service_url, fileId);
		url = RestClient.systemApiUrl(url);
		return url;
	}

	public static String formatCardNo(String cardNo) {
		if (cardNo.length() != 16) {
			return cardNo;
		}

		StringBuilder sb = new StringBuilder();
		sb.append(cardNo.substring(0, 4));
		sb.append("-");
		sb.append(cardNo.substring(4, 8));
		sb.append("-");
		sb.append(cardNo.substring(8, 12));
		sb.append("-");
		sb.append(cardNo.substring(12));
		return sb.toString();
	}

	/**
	 * 
	 * @param imageURL
	 * @return
	 */
	public static Bitmap getBitmapFromUrl(String fileId) {
		String service_url = "common/getfilestream/%s";

		String imageURL = WorldUtilities.format(service_url, fileId);
		imageURL = RestClient.apiUrl(imageURL);

		URL myImageURL = null;

		try {
			myImageURL = new URL(imageURL);
		} catch (MalformedURLException error) {
			error.printStackTrace();
		}

		Bitmap myBitmap = null;
		// InputStream in = null;
		// BufferedOutputStream out = null;

		try {

			HttpURLConnection connection = (HttpURLConnection) myImageURL.openConnection();
			connection.setDoInput(true);
			connection.connect();

			InputStream input = myImageURL.openStream();
			myBitmap = BitmapFactory.decodeStream(input);

			/*
			 * DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet
			 * request = new HttpGet(imageURL); HttpResponse response =
			 * httpClient.execute(request);
			 * 
			 * InputStream input = response.getEntity().getContent(); myBitmap =
			 * BitmapFactory.decodeStream(input);
			 */

		} catch (IOException e) {
			e.printStackTrace();
		}

		return myBitmap;
	}

	public static String parseRestString(String value) {
		return value.replace("\"", "");
	}

	/**
	 * 
	 * @param context
	 * @param urlString
	 * @return
	 */
	public static Bitmap getBitmap(Context context, String fileId) {
		String urlString = getBitmapUrl(fileId);
		String filename = fileId;

		File cacheDir = null;

		try {
			// Find the dir to save cached images
			if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
				cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "Android/data/LazyList");
			} else {
				cacheDir = context.getCacheDir();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (cacheDir == null) {
			return null;
		}

		if (!cacheDir.exists())
			cacheDir.mkdirs();

		File f = new File(cacheDir, filename);
		try {
			if (!f.exists()) {
				Bitmap bitmap = null;
				InputStream is = new URL(urlString).openStream();
				OutputStream os = new FileOutputStream(f);
				copyStream(is, os);
				os.close();
				bitmap = decodeFile(f);

				if (bitmap != null) {
					Log.i("getBitmap", bitmap == null ? "NULL" : "NOTNULL");
				}

				return bitmap;
			} else {
				Bitmap bitmap = decodeFile(f);
				return bitmap;
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	// decodes image and scales it to reduce memory consumption
	private static Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;

			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);

		} catch (FileNotFoundException e) {
		}
		return null;
	}

	// get Rounded bitmap [native bitmap]
	public static Bitmap getRoundedBitmap(Bitmap bm, int scale) {
		return getRoundedRectBitmap(bm, scale);
	}

	// set rounded bitmap
	public static Bitmap getRoundedRectBitmap(Bitmap bitmap, int pixels) {
		// declare variable
		int color;
		Paint paint;
		Rect rect;
		RectF rectF;
		Bitmap result;
		Canvas canvas;
		float roundPx;

		result = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
		canvas = new Canvas(result);

		color = 0xff424242;
		paint = new Paint();
		rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		rectF = new RectF(rect);
		roundPx = pixels;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return result;
	}

	// end set rounded bitmap

	// check email

	@SuppressWarnings("unused")
	public static Bitmap byte2bitmap(byte[] data) {
		InputStream inputStream = new ByteArrayInputStream(data);
		Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
		return WorldUtilities.getRoundedBitmap(bitmap, 10);
	}

	public static String encodeImage(byte[] data) {
		return Base64.encodeToString(data, Base64.DEFAULT);
	}

	public static void recycl1e(ImageView iv) {
		if (iv != null) {
			Drawable drawable = iv.getDrawable();
			if (drawable instanceof BitmapDrawable) {

				Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
				if (null != bitmap && !bitmap.isRecycled()) {
					bitmap.recycle();
					bitmap = null;
					iv.setImageBitmap(null);
					iv.setImageDrawable(null);
				}

			}
		}
	}


}
